package com.zoe.vhr.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zoe.vhr.util.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/08/01
 * @Description 没有认证的时候，直接返回结果给用户,不做重定向处理
 */
@Configuration
public class MyAuthenticationEntryPointPoint implements AuthenticationEntryPoint {
    private ObjectMapper p = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        if (authException instanceof InsufficientAuthenticationException) {
            writer.write(p.writeValueAsString(R.unauthorized("未通过认证,请先登录MyAuthenticationEntryPointPoint")));
        }
        writer.flush();
        writer.close();
    }
}
